package demo.android.com.mvpdemo.RxJava;

import android.support.annotation.NonNull;
import android.util.Log;

/**
 * Created by Vya on 2018/1/26 0026.
 */

public class ObserverbleMap<T,R> extends Observable<R> {

    final Observable<T> source;
    final Function<T, R> function;
    public ObserverbleMap(Observable<T> source, Function<T, R> function) {
        this.source = source;
        this.function = function;
    }

    @Override
    protected void subscribeActual(Observer<R> observer) {
        //这里的source就是ObservableJust
        Log.e("wangyan","ObserverbleMap--->>subscribeActual");
        source.subscribe(new MapObserver(observer,function)); //这里还要给observer包一层
    }

    private class MapObserver<T> implements Observer<T>{
        final Observer<R> observer;
        final Function<T, R> function;

        public MapObserver(Observer<R> source, Function<T, R> function) {
            this.observer = source;
            this.function = function;
        }

        @Override
        public void onNext(@NonNull T item) {
            // item 是 String xxxUrl
            //要去转换 String -> Bitmap
            R applyR = null;
            try {
                applyR = function.apply(item);
                // 把Bitmap传出去
                observer.onNext(applyR); //调用下一层的Observer的onNext方法
            } catch (Exception e) {
                e.printStackTrace();
                observer.onError(e);
            }

        }

        @Override
        public void onError(@NonNull Throwable e) {
            Log.e("wangyan",e.getMessage());
            observer.onError(e);
        }

        @Override
        public void onSubscribe() {
            observer.onSubscribe();
        }

        @Override
        public void onComplete() {
            observer.onComplete();
        }


    }
}
